package flex.cc.store.controller;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.basicinformation.entity.ServiceConfigEntity;
import flex.cc.basicinformation.service.ServiceConfigService;
import flex.cc.common.utils.CommonUtils;
import flex.cc.core.support.BaseController;
import flex.cc.store.dto.entity.StoreQrEntity;
import flex.cc.store.dto.vo.BookingInfoVo;
import flex.cc.store.dto.vo.StoreCouponVo;
import flex.cc.store.dto.vo.StoreInfoVo;
import flex.cc.store.service.BookingInfoService;
import flex.cc.store.service.StoreCouponService;
import flex.cc.store.service.StoreInfoService;
import flex.cc.store.service.StoreQrService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import sun.misc.BASE64Decoder;

/**
 * @author wkangle
 * @className StoreServiceController
 * @description 到店类服务模块
 * @time 2021-12-15 14:32:14
 */
@SuppressWarnings("restriction")
@RestController
@RequestMapping(value = "/vehicleSvr/storeService/wechat")
public class StoreServiceController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StoreServiceController.class);

    @Autowired
    private StoreCouponService storeCouponService;
    @Autowired
    private BookingInfoService bookingInfoService;
    @Autowired
    private StoreInfoService storeInfoService;
    @Resource
	private StoreQrService qrService;
    @Autowired
    private DictCodeService dictCodeService;
    @Autowired
    private ServiceConfigService serviceConfigService;

    /**
	 *
	 * @author WANGCONG
	 * 2022年1月20日下午16:07:19
	 * @desc C端加密链接生成
	 */
    @RequestMapping("/init")
	@ResponseBody
	public String init(@RequestBody Map<String,String> params) throws Exception {
    	String packageCode = params.get("packageCode");
    	String orderId = params.get("orderId");
    	Map<String, Object> body = new HashMap<String, Object>();
		body.put("apiSource", "ZXHY");
		body.put("card_code", packageCode); //服务包编码
		body.put("redirectUrl", "https://mclub.sinosig.com/couponList");
		body.put("orderId", orderId); //订单号
		body.put("sign", "03021F3ABE5DE761F5D50318B291D207");
		body.put("signType", "MD5");
		body.put("telephone", "15510053451");
		body.put("source", "ZXHY");
		body.put("customerNo", "");
		String json = CommonUtils.toJSONString(body);
		byte[] bytes = json.getBytes();
    	return Base64.getEncoder().encodeToString(bytes);
    }

    /**
	 *
	 * @author WANGCONG
	 * 2021年12月23日下午14:06:39
	 * @desc 商城跳转请求参数解密
	 */
	@PostMapping(value = "/initDecrypt/{urlParams}")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "商城URL解密")
    public Wrapper<Map<String, Object>> initDecrypt(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String urlParams) {
		logger.info("StoreServiceController 商城URL解密");
		logger.info("解密前报文---"+urlParams);
		BASE64Decoder base64 = new BASE64Decoder();
        Map<String, Object> result = new HashMap<>();
    	try {
			byte[] bytes = base64.decodeBuffer(urlParams);
			result.put("code", "0000");
            result.put("params", JSONObject.parse(new String(bytes)));
            logger.info("解密后报文---"+result.get("params"));
			return WrapMapper.ok(result);
		} catch (IOException e) {
			e.printStackTrace();
            result.put("code", "0001");
            result.put("params", "URL解码失败");
			return WrapMapper.ok(result);
		}
    }

	//前台传过来的查询参数：orderId、redirectUrl、packageCodeCF、status(1-待使用、2-已使用、3-已过期，初始默认1)
    @PostMapping(value = "/queryCouponList")
    @ApiOperation(httpMethod = "POST", value = "查询服务卡券列表")
    public Wrapper<List<StoreCouponVo>> queryCouponList(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("StoreServiceController -- queryCouponList() ====> {}", reqVo);
        List<StoreCouponVo> list = storeCouponService.queryCouponList(reqVo);
        return WrapMapper.ok(list);
    }

    @PostMapping(value = "/openBooking")
    @ApiOperation(httpMethod = "POST", value = "预约提交页面")
    public Wrapper<BookingInfoVo> openBooking(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody StoreCouponVo reqVo) {
        logger.info("StoreServiceController -- openBooking() ====> {}", reqVo);
        BookingInfoVo bookingInfoVo = bookingInfoService.openBooking(reqVo);
        return WrapMapper.ok(bookingInfoVo);
    }

    @PostMapping(value = "/bookingInfo")
    @ApiOperation(httpMethod = "POST", value = "预约信息页面")
    public Wrapper<BookingInfoVo> bookingInfo(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("StoreServiceController -- bookingInfo() ====> {}", reqVo);
        BookingInfoVo bookingInfoVo = bookingInfoService.bookingInfo(reqVo);
        return WrapMapper.ok(bookingInfoVo);
    }

    @PostMapping(value = "/chooseStore")
    @ApiOperation(httpMethod = "POST", value = "选择门店页面")
    public Wrapper<List<StoreInfoVo>> chooseStore(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("StoreServiceController -- chooseStore() ====> {}", reqVo);
        List<StoreInfoVo> list = storeInfoService.queryStoreList(reqVo);
        return WrapMapper.ok(list);
    }

    @PostMapping(value = "/saveBooking")
    @ApiOperation(httpMethod = "POST", value = "预约提交")
    public Wrapper<Map<String, String>> saveBooking(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("StoreServiceController -- saveBooking() ====> {}", reqVo);
        Map<String, String> saveBooking = bookingInfoService.saveBooking(reqVo);
        return WrapMapper.ok(saveBooking);
    }

    @GetMapping(value = "/openQR")
    @ApiOperation(httpMethod = "GET", value = "我已到店页面")
    public Wrapper<Map<String, Object>> openQR(@ApiParam(name = "reqVo", value = "请求信息") @RequestParam(name = "couponNum") String couponNum) {
        logger.info("StoreServiceController -- openQR() ====> {}", couponNum);
        //防刷：判断当前卡券码是否核销确认通过，如果已通过，不允许重复刷码
        Map<String, Object> params = new HashMap<String, Object>();
		params.put("couponNum", couponNum);
		params.put("status", "1"); //是否已核销通过，0-否，1-是
		StoreQrEntity qrEntity = qrService.getOneByParams(params);
		Map<String, Object> couponQR = new HashMap<String, Object>();
		if(qrEntity!=null){
			couponQR.put("code", "9998");
			couponQR.put("message", "卡券已核销确认通过");
		}else{
			couponQR = storeCouponService.couponQR(couponNum);
		}
        return WrapMapper.ok(couponQR);
    }

    /**
     * @description 根据服务项目id查询服务项目的使用规则【2.2-服务包配置需求】
     * @param activityId 服务项目编号
     * @return
     * @author wkangle
     * @time 2022/03/02 0002 14:13
     * @exception/throws
    */
    @GetMapping(value = "/showActivityRule")
    @ApiOperation(httpMethod = "GET", value = "根据服务项目id查询服务项目的使用规则")
    public Wrapper<ServiceConfigEntity> showActivityRule(@ApiParam(name = "reqVo", value = "请求信息") @RequestParam(name = "activityId") String activityId) {
        logger.info("StoreServiceController -- showActivityRule() ====> ", activityId);
        //Map<String, Object> dictCodeParams = new HashMap<String, Object>();
        //dictCodeParams.put("typeCode", "activityRule");
        //dictCodeParams.put("value1", activityId);
        //List<DictCodeEntity> list = dictCodeService.queryDictCodeListByParams(dictCodeParams);
        //return WrapMapper.ok(list);
	    Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", '0');
        params.put("serviceCode", activityId);
        ServiceConfigEntity serviceConfigEntity = serviceConfigService.getOneByParams(params);
        return WrapMapper.ok(serviceConfigEntity);
    }

    @GetMapping(value = "/queryCouponFestivalTips")
    @ApiOperation(httpMethod = "GET", value = "节假日弹框提示")
    public Wrapper<DictCodeEntity> queryCouponFestivalTips() {
        DictCodeEntity couponFestivalTips = dictCodeService.queryCouponFestivalTips();
        return WrapMapper.ok(couponFestivalTips);
    }


}
